package cn.cvs.web;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.util.Constants;
import cn.cvs.util.DataTransfer;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class SysUserController {

    @Resource
     SysUserService sysUserService;

    @Resource
    SysRoleService sysRoleService;


    //跳转到登陆页面
    @RequestMapping(value = {"/toLogin","/"})
     public String toLogin(){
        System.out.println("执行控制器的toLogin");
        return "login";
     }

     //登陆
    @RequestMapping("/login")
     public String doLogin(@RequestParam String account,
                           @RequestParam String password, HttpSession session,
                           Model model){
         SysUser sysUser = sysUserService.queryUser(account, password);
         if(sysUser!=null){
              //登陆成功
              //将登陆的用户放入Session中
             session.setAttribute(Constants.USER_SESSION, sysUser);
              //跳转到主页面 frame.jsp
             return "frame";
         }else{
             //登陆失败
             //绑定一个错误消息
             model.addAttribute("error",
                     "用户名或密码错误");
             //跳转回登陆页面login.jsp
             return "login";
         }
     }

     //跳转到主页面
    @RequestMapping("/sys/toMain")
    public String toMain(){
         return "frame";
    }

    //注销登陆
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        Object user = session.getAttribute(Constants.USER_SESSION);
        if(user!=null){
              //登陆的状态
             session.removeAttribute(Constants.USER_SESSION);
        }
        //转发到某个请求
        return "forward:/toLogin";
        //重定向到某个请求
        //return "redirect: /**"
    }


     //局部异常处理
     //只会处理当前控制器抛出的异常
    @ExceptionHandler(value = {Exception.class})
    public String exceptionHandle(Exception e, Model model){
            e.printStackTrace();
            model.addAttribute("exception", e);
            return "sysError";
    }
    //根据输入算输出
    //输入: 入参（页面传给后台控制器的参数）
    //输出: 出参 (后台传给页面的参数)
    // 对于前后台不分离的系统（使用jsp...)
    //指的就是放入 作用域中的数据,就是页面el表达式中的变量
    //用户列表
    @RequestMapping("/sys/user/list")
    public String list(@RequestParam(value = "queryRealName",required = false) String realName,
                       @RequestParam(value = "queryRoleId",required = false) Integer roleId,
                       @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageNo,
                        Model model){
           //出参 queryRealName
            model.addAttribute("queryRealName",realName);
           //出参 queryRoleId
            model.addAttribute("queryRoleId",roleId);
           // 出参 roleList 角色类表(全部的角色)
          List<SysRole> sysRoles = sysRoleService.queryAllRoles();
           model.addAttribute("roleList",sysRoles);
        //出参 userList  用户列表
        List<SysUser> sysUsers
                = sysUserService.queryUsers(realName, roleId, pageNo, Constants.pageSize);
        model.addAttribute("userList",sysUsers);
        //totalCount (参与条件分页)总记录数
        int count = sysUserService.queryCount(realName, roleId);
        model.addAttribute("totalCount",count);
        //currentPageNo 当前页码 就是入参 pageIndex
        model.addAttribute("currentPageNo",pageNo);
        //totalPageCount 总页数
        PageSupport pageSupport = new PageSupport();
        //设置pageSize 一页几条记录
        pageSupport.setPageSize(Constants.pageSize);
        //设置参与分页的总记录数
        pageSupport.setTotalCount(count);
        //获得总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "sysUser/list";
    }


    //跳转到添加用户的页面
    @RequestMapping("/sys/user/toAdd")
    public String toAddUser(@ModelAttribute("sysUser") SysUser sysUser, Model model){
        //查询角色列表
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("sysRoles",sysRoles);
        model.addAttribute("sysUser", new SysUser());
        return "sysUser/add";
    }

    //添加用户

    /**
     *
     * 对页面表单提交的数据(对象SysUser) 加注解@Valid
     * spring框架就会对对象中封装的数据进行自动验证
     * 最后将验证的结果封装 到BindingResult对象中
     * BindingResult 参数必须紧跟在表单参数的后面
     *
     * @return
     */
    /*@PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult,
                          HttpSession session,
                          HttpServletRequest request,
                          Model model,
                          @RequestParam(value = "idPic",required = false) MultipartFile idPic){
        // System.out.println(sysUser);
        //验证用户是否登陆
        SysUser loginUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if(loginUser==null){
             //还没有登陆
            model.addAttribute("error", "请登录后操作！");
             return "forward:/toLogin";
        }
        //查看后台验证的结果
         if(bindingResult.hasErrors()){
              //后台验证错误
               throw new RuntimeException("后台数据校验错误！");
         }

           //保存图片
          //idPic.transferTo(new File("xxx"));
           //图片命名规则
           //时间错_原名
           //创建上传文件的新名字
           String saveFileName = System.currentTimeMillis()
                   +"_" +idPic.getOriginalFilename();
           //服务器的保存位置
           //  /工程目录/statics/uploadFiles/
           //  工程目录 是指该工程在服务器上的具体位置
           //  D:/web_server/tomcat9/webapps/ssmdemo-kf01/
          //D:/web_server/tomcat9/webapps/ssmdemo-kf01/statics/uploadFiles/
        String realPath = request.getSession()
                .getServletContext()
                .getRealPath("statics"+File.separator+"uploadFiles");
        //创建保存的目录
          File dir = new File(realPath);
          if(!dir.exists()){
              //不存在就创建
                dir.mkdirs();
          }
          //创建要保存到服务器上的文件
         File saveFile = new File(dir,saveFileName);
         //保存文件
        try {
            idPic.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("保存图片失败",e);
        }
         //创建保存到数据库的图片路径信息
        String idPicPath = File.separator+"statics"+File.separator
                +"uploadFiles"+File.separator+saveFileName;
         sysUser.setIdPicPath(idPicPath);
        //设置创建的时间
        sysUser.setCreatedTime(new Date());
        //设置创建人的id
        sysUser.setCreatedUserId(loginUser.getId());
         //添加用户
        int i = sysUserService.addUser(sysUser);
        if(i>0){
             //添加用户成功
             //重定向回用户列表
            return "redirect:/sys/user/list";
        }else{
             //添加用户失败
            throw  new RuntimeException("添加用户失败，请稍后再试!");
        }
    }*/

    @PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult,
                          HttpSession session,
                          HttpServletRequest request,
                          Model model,
                          @RequestParam(value = "attaches",required = false) MultipartFile[] attaches){
        // System.out.println(sysUser);
        //验证用户是否登陆
        SysUser loginUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if(loginUser==null){
            //还没有登陆
            model.addAttribute("error", "请登录后操作！");
            return "forward:/toLogin";
        }
        //查看后台验证的结果
        if(bindingResult.hasErrors()){
            //后台验证错误
            throw new RuntimeException("后台数据校验错误！");
        }

        for (int i = 0; i < attaches.length; i++) {
            //保存图片
            //idPic.transferTo(new File("xxx"));
            //图片命名规则
            //时间错_原名
            //创建上传文件的新名字
            String saveFileName = System.currentTimeMillis()
                    +"_" +attaches[i].getOriginalFilename();
            //服务器的保存位置
            //  /工程目录/statics/uploadFiles/
            //  工程目录 是指该工程在服务器上的具体位置
            //  D:/web_server/tomcat9/webapps/ssmdemo-kf01/
            //D:/web_server/tomcat9/webapps/ssmdemo-kf01/statics/uploadFiles/
            String realPath = request.getSession()
                    .getServletContext()
                    .getRealPath("statics"+File.separator+"uploadFiles");
            //创建保存的目录
            File dir = new File(realPath);
            if(!dir.exists()){
                //不存在就创建
                dir.mkdirs();
            }
            //创建要保存到服务器上的文件
            File saveFile = new File(dir,saveFileName);
            //保存文件
            try {
                attaches[i].transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("保存图片失败",e);
            }
            //创建保存到数据库的图片路径信息
            String path = File.separator+"statics"+File.separator
                    +"uploadFiles"+File.separator+saveFileName;
            if(i==0){
                sysUser.setIdPicPath(path);
            }else{
                sysUser.setWorkPicPath(path);
            }

        }


        //设置创建的时间
        sysUser.setCreatedTime(new Date());
        //设置创建人的id
        sysUser.setCreatedUserId(loginUser.getId());
        //添加用户
        int i = sysUserService.addUser(sysUser);
        if(i>0){
            //添加用户成功
            //重定向回用户列表
            return "redirect:/sys/user/list";
        }else{
            //添加用户失败
            throw  new RuntimeException("添加用户失败，请稍后再试!");
        }
    }


    //跳转到修改页面
    @RequestMapping("/sys/user/toUpdate")
    public String toUpdateUser(@RequestParam("uid") Integer id, Model model){
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser",sysUser);
        //查询出所有的角色
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("sysRoles",sysRoles);
        return "sysUser/update";
    }

    //保存用户
    @PostMapping("/sys/user/update")
    public String  updateUser(SysUser sysUser,
                              HttpSession session,
                              Model model){
             //登陆验证
        SysUser loginUser =
        (SysUser)session.getAttribute(Constants.USER_SESSION);
        if(loginUser==null){
            //还没有登陆
            model.addAttribute("error", "请登录后操作！");
            return "forward:/toLogin";
        }
        //修改时间
        sysUser.setUpdatedTime(new Date());
        //修改人的id
        sysUser.setUpdatedUserId(loginUser.getId());
        int i = sysUserService.updateUser(sysUser);
        if(i>0){
             //修改成功
             //重定向到用户列表
            return "redirect:/sys/user/list";
        }else{
             //修改失败-->抛异常
            throw new RuntimeException("修改失败，请稍后再试!");
        }
    }

    //查看用户 同步
    @GetMapping("/sys/user/view/{uid}")
     public String viewUser(@PathVariable("uid") Integer id, Model model){
             //依据id查询用户对象
        SysUser sysUser = sysUserService.queryById(id);
         model.addAttribute("sysUser",sysUser);
         return "sysUser/view";
    }


    //验证account是否唯一
    @ResponseBody //标识这个方法是处理异步请求，返回结果不走视图解析器
    @GetMapping("/sys/user/userExist")
    public Object userExists(@RequestParam String account){
           //定义一个返回结果
        Map<String,Object> resultMap = new HashMap<>();
        if(StringUtils.isEmpty(account)){
            resultMap.put("exist","-1");
            resultMap.put("msg","账户不能为空");
            return JSON.toJSONString(resultMap);
        }

        try {
            int count = sysUserService.queryUserCount(account);
            if(count==1){
                 //不可用
                resultMap.put("exist", "1");
            }else{
                  //0 可用
                resultMap.put("exist","0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("exist","-1");
            resultMap.put("msg", e.getMessage());
        }
        return JSON.toJSONString(resultMap);
    }


    //异步查看用户信息
    @ResponseBody
    @GetMapping("/sys/user/{uid}/view")
    public Object   asyViewUser(@PathVariable("uid") Integer id){
            //返回对象
        DataTransfer<SysUser> dto = new DataTransfer<>();
        try {
            SysUser sysUser = sysUserService.queryById(id);
            if(sysUser==null){
                   dto.setStatus("nodata");
                   return JSON.toJSONString(dto);
            }
            dto.setStatus("ok");
            dto.setData(sysUser);
            return JSON.toJSONString(dto);
        } catch (Exception e) {
            e.printStackTrace();
            dto.setStatus("failed");
            return JSON.toJSONString(dto);
        }
    }


    //异步删除用户
    @ResponseBody
    @DeleteMapping("/sys/user/{uid}")
    public Object deleteUser(@PathVariable("uid") Integer id,
                             HttpSession session,
                              HttpServletRequest request){
           //返回值对象
            Map<String,Object> resultMap = new HashMap<>();
         SysUser loginUser =
          (SysUser)session.getAttribute(Constants.USER_SESSION);
         //判断是否登陆
         if(loginUser==null){
             resultMap.put("delResult", "noLogin");
             resultMap.put("msg", "请登陆后再操作");
             return JSON.toJSONString(resultMap);
         }
        //判断是否是管理员
         if(loginUser.getRoleId()!=1){
              //非管理员
             resultMap.put("delResult","notAdmin");
             resultMap.put("msg", "非管理员不能删除用户");
             return JSON.toJSONString(resultMap);
         }

        SysUser sysUser = sysUserService.queryById(id);
         if(sysUser==null){
               resultMap.put("delResult","notexist");
               return JSON.toJSONString(resultMap);
         }
        //删除的用户不能是管理员
         if(sysUser.getRoleId()==1){
               //删除的是一个管理员
              resultMap.put("delResult","delAdmin");
             resultMap.put("msg", "不能删除管理员");
             return JSON.toJSONString(resultMap);
         }
           //执行删除操作
        int i = sysUserService.deleteUser(id, request);
         if(i>0){
              //删除成功
             resultMap.put("delResult","true");
         }else{
              //0
              //删除失败
             resultMap.put("delResult","false");
         }
       return JSON.toJSONString(resultMap);
    }
}
